package cn.chinaunicom.admin.interceptor;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;

import cn.chinaunicom.admin.entity.AppServer;
import cn.chinaunicom.admin.utils.AppContextHandler;
import cn.chinaunicom.fast.common.constant.RedisKeys;
import cn.chinaunicom.fast.common.utils.FebsUtil;
import cn.chinaunicom.fast.common.utils.MyCache;
import lombok.extern.slf4j.Slf4j;

/**
 * @ProjectName: esay-secret-server
 * @Package: cn.chinaunicom.admin.interceptor
 * @ClassName: AppInterceptor
 * @Description: java类作用描述
 * @Author: wangjc
 * @CreateDate: 2023/11/24
 * @UpdateUser: wangjc
 * @UpdateDate: 2023/11/24
 * @UpdateRemark: 更新内容
 * @Version: 1.0
 */
@Slf4j
public class AppInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        log.info("当前uri: {}", requestURI);

        Enumeration<String> headerNames = request.getHeaderNames();
        while(headerNames.hasMoreElements()) {
            String s = headerNames.nextElement();
            log.debug("Received header name: {} value: {}", s, request.getHeader(s));
        }
        String ipAddress = FebsUtil.getServerHttpRequestIpAddress(request);
        log.debug("Received ip address: {}", ipAddress);

        String accessToken = request.getParameter("accessToken");
        log.debug("Access token: {}", accessToken);

        AppServer cache = (AppServer) MyCache.getInstance().getCache(RedisKeys.APP_LONIN_INFO + accessToken);
        AppContextHandler.getInstance().setApp(cache);
        if( cache != null) {
            log.debug("token有效，查询到当前token的缓存，存储到app上下文中");
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AppContextHandler.getInstance().clear();
    }
}
